package routers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func LoadUpload(engine *gin.Engine) {
	engine.MaxMultipartMemory = 8 << 20

	engine.GET("/upload", func(ctx *gin.Context) {
		ctx.HTML(http.StatusOK, "upload.html", gin.H{})
	})

	engine.POST("/upload", func(ctx *gin.Context) {

		form, err := ctx.MultipartForm()
		if err != nil {
			ctx.String(500, "上传图片出错")
		}
		fileHeaders := form.File["files"]
		for _, file := range fileHeaders {
			if err := ctx.SaveUploadedFile(file, "./upload/"+file.Filename); err != nil {
				ctx.String(http.StatusBadRequest, fmt.Sprintf("upload err %s", err.Error()))
				return
			}
		}
		ctx.String(200, fmt.Sprintf("upload ok %d files", len(fileHeaders)))

		// 另一种写法
		//_, header, err := ctx.Request.FormFile("file")
		//if err != nil {
		//	ctx.String(500, "上传图片出错")
		//}
		//ctx.SaveUploadedFile(header, "./upload/"+header.Filename)
		//ctx.String(http.StatusOK, "upload success "+header.Filename)
	})
}
